#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_rwlock_t lock;

void *fun1(void *);
void *fun2(void *);
void *fun3(void *);
void *fun4(void *);

int main(int argc, char *argv[]) {
  pthread_t tid[4];
  pthread_rwlock_init(&lock,NULL);

  pthread_create(&tid[0], NULL, fun1, NULL);
  pthread_create(&tid[1], NULL, fun2, NULL);
  pthread_create(&tid[2], NULL, fun3, NULL);
  pthread_create(&tid[4], NULL, fun4, NULL);

  pthread_join(tid[0], NULL);
  pthread_join(tid[1], NULL);
  pthread_join(tid[2], NULL);
  pthread_join(tid[3], NULL);

  pthread_exit(NULL);
}

void *fun1(void *argv) {

  sleep(3);
  while (1) {

    pthread_rwlock_rdlock(&lock);
    printf("process 1 get rdlock\n");

    pthread_rwlock_unlock(&lock);
    
    printf("process 1 unlock\n");
  }

  pthread_exit(NULL);
}

void *fun2(void *argv) {
  sleep(3);
  while (1) {
    pthread_rwlock_wrlock(&lock);
    printf("process 2 get wrlock\n");

    pthread_rwlock_unlock(&lock);
    printf("process 2 unlock\n");
  }

  pthread_exit(NULL);
}

void *fun3(void *argv) {
  sleep(3);
  while (1) {
    pthread_rwlock_wrlock(&lock);
    printf("process 3 get wrlock\n");

    pthread_rwlock_unlock(&lock);
    printf("process 3 unlock\n");
  }

  pthread_exit(NULL);
}
void *fun4(void *argv) {

  sleep(3);
  while (1) {

    pthread_rwlock_rdlock(&lock);
    printf("process 4 get rdlock\n");

    pthread_rwlock_unlock(&lock);
    printf("process 4 unlock\n");
  }

  pthread_exit(NULL);
}
